import { Request, Response } from 'express';
import { parse } from 'url';
import { RightsListItem, RightsListParams } from '@/pages/Rights/data';

// mock rightsListDataSource
const genList = (current: number, pageSize: number) => {
  const rightsListDataSource: RightsListItem[] = [];

  for (let i = 0; i < pageSize; i++) {
    const index = (current - 1) * 10 + i;
    rightsListDataSource.push({
      id: index,
      name: `李 ${index}`,
      phone: `187${index}`,
      rights: Math.floor(Math.random() * 10 + 1) % 2 === 0 ? 'admin' : '管理员',
      updatedAt: new Date(),
      createdAt: new Date(),
    });
  }
  rightsListDataSource.reverse();
  return rightsListDataSource;
};

let rightsListDataSource = genList(1, 100);

function getRights(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  // 默认分页数据
  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query as unknown as RightsListParams;

  let dataSource: RightsListItem[] = [...rightsListDataSource];

  // 根据用户姓名查询
  if (params.name) {
    dataSource = [...rightsListDataSource].filter((data) => data.name.includes(params.name || ''));
  }

  // 根据手机号码查询
  if (params.phone) {
    dataSource = [...rightsListDataSource].filter((data) =>
      data.phone.includes(params.phone || ''),
    );
  }

  // 根据权限查询
  if (params.rights) {
    dataSource = [...rightsListDataSource].filter((data) =>
      data.rights.includes(params.rights || ''),
    );
  }

  let _dataSource = dataSource.slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  const sorter = JSON.parse(params.sorter as any);
  if (sorter) {
    _dataSource = _dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as {
      [key: string]: string[];
    };
    if (Object.keys(filter).length > 0) {
      _dataSource = _dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }

  const result = {
    data: _dataSource,
    total: dataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };

  return res.json(result);
}

function postRights(req: Request, res: Response, u: string, b: Request) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  const { method, id, phone, name, rights } = body;

  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'add':
      (() => {
        const newRights = {
          id: rightsListDataSource.length,
          name,
          phone,
          rights,
          updatedAt: new Date(),
          createdAt: new Date(),
        };
        rightsListDataSource.unshift(newRights);
        return res.json(newRights);
      })();
      return;

    case 'update':
      (() => {
        let newRights = {};
        rightsListDataSource = rightsListDataSource.map((item) => {
          if (item.id === id) {
            newRights = { ...item, name, phone, rights };
            return { ...item, name, phone, rights };
          }
          return item;
        });
        return res.json(newRights);
      })();
      return;

    case 'delete':
      rightsListDataSource = rightsListDataSource.filter((item) => id !== item.id);
      break;
    default:
      break;
  }

  const result = {
    list: rightsListDataSource,
    pagination: {
      total: rightsListDataSource.length,
    },
  };

  res.json(result);
}

export default {
  'GET /api/rights': getRights,
  'POST /api/rights': postRights,
};
